/**
 * 
 */
package org.mspring.crm.client;

import org.mspring.crm.client.model.ItemModel;
import org.mspring.crm.client.mvc.ApplicationController;
import org.mspring.crm.client.mvc.ContentController;

import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.Timer;

/**
 * @author Gao Youbo
 * @since 2012-3-2
 * 
 */
public class Application implements EntryPoint {

    private Dispatcher dispatcher;

    /*
     * (non-Javadoc)
     * 
     * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
     */
    @Override
    public void onModuleLoad() {
        if (!GWT.isScript()) {
            GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                public void onUncaughtException(Throwable e) {
                    e.printStackTrace();
                }
            });
        }

        if ("access".equals(GXT.getThemeId())) {
            Timer t = new Timer() {
                @Override
                public void run() {
                    buildApp();
                }
            };
            t.schedule(500);
        } else {
            buildApp();
        }
    }

    private void buildApp() {
        dispatcher = Dispatcher.get();
        dispatcher.addController(new ApplicationController());
        dispatcher.addController(new ContentController());

        dispatcher.dispatch(AppEvents.Login);
        GXT.hideLoadingPanel("loading");
    }

    public static void showPage(ItemModel item) {
        if (item != null && item.getView() != null && !"".equals(item.getView().trim())) {
            AppEvent appEvent = new AppEvent(AppEvents.ShowPage, item);
            appEvent.setHistoryEvent(true);
            appEvent.setToken(item.getId().toString());
            Dispatcher.forwardEvent(appEvent);
        }
    }
}
